package com.lu.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lu.common.constants.ScheduleConstants;
import com.lu.common.redis.CacheService;
import com.lu.model.schedule.dto.Task;
import com.lu.model.schedule.pojo.Taskinfo;
import com.lu.model.schedule.pojo.TaskinfoLogs;
import com.lu.schedule.mapper.TaskinfoLogsMapper;
import com.lu.schedule.mapper.TaskinfoMapper;
import com.lu.schedule.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Slf4j
@Service
@Transactional
public class TaskServiceImpl implements ITaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;


    /**
     * 添加任务
     * @param task 任务对象
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1. 添加到数据库
        boolean dbFlag = addToDb(task);

        //2. 添加到redis
        if (dbFlag) {
            addToCache(task);
        }
        //2.1
        return task.getTaskId();
    }


    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        //删除数据库任务数据并且更新日志,这里抽取成一个通用的方法
        Task task = updateTaskDb(taskId, ScheduleConstants.EXECUTED);

        //删除redis缓存的数据
        if (task != null) {
            removeRedis(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 消费任务
     * @param type 类型
     * @param priority 优先级
     * @return
     */
    @Override
    public Task pullTask(Integer type, Integer priority) {
        Task task = null;
        try {
            String key = type + "_" + priority;
            String taskjson = cacheService.lRightPop(ScheduleConstants.CURRENT + key);
            if (StringUtils.isNotBlank(taskjson)) {
                task = JSON.parseObject(taskjson, Task.class);
                //更新日志
                updateTaskDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("task pull exception");
        }
        return task;
    }


    /**
     * 定时刷新任务
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        log.info("{}执行了定时任务", System.currentTimeMillis() / 1000);
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("未来数据定时刷新---定时任务");
            //获取延时的任务future_
            Set<String> futureKeylist = cacheService.scan(ScheduleConstants.FUTURE + "*/");
            //符合条件的拉取消费
            for (String key : futureKeylist) {
                String currentKey = ScheduleConstants.CURRENT + key.split(ScheduleConstants.FUTURE)[1];
                Set<String> taskList = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
                if (!taskList.isEmpty()) {
                    //添加到消费队列
                    cacheService.refreshWithPipeline(key, currentKey, taskList);
                    log.info("{}已进入消费队列", currentKey);
                }
            }
        }
    }


    /**
     * 同步数据库数据到缓存
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void flushDbCache() {
        //1.清除原有缓存
        cleanCache();
        log.info("开始同步数据库数据到缓存");
        //符合同步条件的
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if (taskinfoList != null && taskinfoList.size() > 0) {
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addToCache(task);
            }
        }


    }


    /**
     * 清除原有缓存
     */
    public void cleanCache() {
        //当前和延时的所有数据
        Set<String> futureKeyList = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> currentKeyList = cacheService.scan(ScheduleConstants.CURRENT + "*");
        cacheService.delete(futureKeyList);
        cacheService.delete(currentKeyList);
    }

    /**
     * 删除redis缓存
     * @param task
     */
    public void removeRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //小于当前时间删除list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.CURRENT + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }

    }

    /**
     * 更新日志
     * @param taskId
     * @param executed
     * @return
     */
    public Task updateTaskDb(long taskId, int executed) {
        Task task = null;
        try {
            //删除数据库数据
            taskinfoMapper.deleteById(taskId);
            //更新日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(executed);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            //返回需要用到的task
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
           log.error("任务{}取消失败", taskId);
        }


        return task;
    }

    /**
     * 添加任务到redis缓存
     * @param task
     * @return
     */
    public void addToCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //延时时间为五分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long time = calendar.getTimeInMillis();
        //任务时间小于当前时间，存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.CURRENT + key, JSON.toJSONString(task));
            //大于存入zset
        } else if (task.getExecuteTime() >= System.currentTimeMillis()) {
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }


    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    public boolean addToDb(Task task) {
        boolean flag = false;
        try {
            //添加到任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置任务id
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }


        return flag;
    }
}
